/*
 * clustering.cpp
 *
 *  Created on: Dec 13, 2012
 *      Author: filipe mutz
 */

#include <cstdio>
#include <cstdlib>
#include "clustering_config.h"
#include "clustering_algorithms/kmeans.h"
#include "clustering_algorithms/random.h"

void
parse_args(char **argv, clustering_config *config)
{
	config->num_points = atoi(argv[2]);
	config->dimension = atoi(argv[3]);
	config->num_clusters = atoi(argv[4]);
}


void
allocate_points(clustering_config config, double ***points)
{
	(*points) = (double **) calloc (config.num_points, sizeof(double*));

	for (int i = 0; i < config.num_points; i++)
		(*points)[i] = (double *) calloc (config.dimension, sizeof(double));
}


void
allocate_cluster_ids(clustering_config config, int **cluster_ids)
{
	(*cluster_ids) = (int *) calloc (config.num_points, sizeof(int));
}


void
read_points(char *filename, clustering_config config, double **points)
{
	FILE *fileptr = fopen(filename, "r");

	for (int i = 0; i < config.num_points; i++)
		for (int j = 0; j < config.dimension; j++)
			fscanf(fileptr, "%lf", &(points[i][j]));

	fclose(fileptr);
}


void
cluster_data(clustering_config config, double **points, int *cluster_ids)
{
	kmeans(config, points, cluster_ids);
	//random(config, points, cluster_ids);
}


void
output_cluster_ids(clustering_config config, int *cluster_ids)
{
	for (int i = 0; i < config.num_points; i++)
		printf("%d\n", cluster_ids[i]);
}


void
free_all_data(clustering_config config, double **points, int *cluster_ids)
{
	for (int i = 0; i < config.num_points; i++)
		free(points[i]);

	free(points);
	free(cluster_ids);
}


int
main(int argc, char *argv[])
{
	clustering_config config;

	double **points;
	int *cluster_ids;

	if (argc < 5)
		exit(printf("Use %s <pontos.dat> <num_points> <dimension> <num-clusters>\n", argv[0]));

	parse_args(argv, &config);
	allocate_points(config, &points);
	allocate_cluster_ids(config, &cluster_ids);
	read_points(argv[1], config, points);
	cluster_data(config, points, cluster_ids);
	output_cluster_ids(config, cluster_ids);
	free_all_data(config, points, cluster_ids);

	return 0;
}



